﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using StreamingClient.Localization;
using StreamingClient.Player;

namespace VlcPlayer
{
    public partial class PlayerPage : PhoneApplicationPage
    {
        private BackgroundWorker bw;

        public PlayerPage()
        {
            InitializeComponent();
        }

        private void GoBack()
        {
            if (CanGoBack && NavigationService.CanGoBack)
            {
                CanGoBack = false;
                try
                {
                    NavigationService.GoBack();
                }
                catch (InvalidOperationException)
                { }
            }
        }

        protected bool CanGoBack { get; set; }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            CanGoBack = true;

            var src = NavigationContext.QueryString["src"];
            var svId = NavigationContext.QueryString["svId"];
            var serverId = int.Parse(svId);
            AttachEvents();
            var VlcServers = (List<VlcSettings>)IsolatedStorageSettings.ApplicationSettings["Servers"];
            var server = VlcServers[serverId];

            PlayerControl.Start(src, server.StreamingSettings);

            if (App.IsTrial)
            {
                ct = new CancelationToken();

                bw = new BackgroundWorker();
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerAsync(ct);
            }
        }
        
        CancelationToken ct;


        private class CancelationToken
        {
            public bool Cancel { get; set; }
        }


        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var ct= (CancelationToken)e.Argument;

                System.Threading.Thread.Sleep(60000);
                if (ct.Cancel)
                {
                    return;
                }
                if (App.IsTrial)
                {
                    Dispatcher.BeginInvoke(
                        () =>
                            {
                                try
                                {
                                    NavigationService.Navigate(new Uri("/BuyPage.xaml", UriKind.Relative));
                                }
                                catch (Exception)
                                {}
                            });
                }

            }
            catch (Exception ex)
            {
                App.WriteExceptionToLog(ex);
            }
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (ct != null)
            {
                ct.Cancel = true;
            }
            base.OnNavigatingFrom(e);
            DetachEvents();
            PlayerControl.CleanUp();
        }


        private void AttachEvents()
        {
            PlayerControl.Ended += new EventHandler(PlayerCtrl_Ended);
            PlayerControl.Failed += new EventHandler<ErrorEventArgs>(PlayerCtrl_Failed);
        }

        private void DetachEvents()
        {
            PlayerControl.Ended -= new EventHandler(PlayerCtrl_Ended);
            PlayerControl.Failed -= new EventHandler<ErrorEventArgs>(PlayerCtrl_Failed);
        }

        void PlayerCtrl_Failed(object sender, ErrorEventArgs e)
        {
            Dispatcher.BeginInvoke(()=>{
            if (e.Exception != null)
            {
                App.WriteExceptionToLog(e.Exception);
            }
            var msg = Localize.GetString("EC_" + e.Error);
            if (e.Exception != null)
            {
                msg += Environment.NewLine + Environment.NewLine + e.Exception.ToString();
            }
            MessageBox.Show(msg, AppResources.Error, MessageBoxButton.OK);
            GoBack();
            })
            ;
        }

        void PlayerCtrl_Ended(object sender, EventArgs e)
        {
            GoBack();
        }       
    }
}